package com.guiwu.controller;

import com.guiwu.dto.ItemDto;
import com.guiwu.entity.Category;
import com.guiwu.entity.Item;
import com.guiwu.entity.User;
import com.guiwu.service.CategoryService;
import com.guiwu.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;

/**
 * 物品管理Web控制器
 * 处理物品相关的页面请求和表单提交
 */
@Controller
@RequestMapping("/item")
public class ItemWebController {

    @Autowired
    private ItemService itemService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 配置数据绑定
     * 处理LocalDate类型的日期绑定
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (text == null || text.trim().isEmpty()) {
                    setValue(null);
                    return;
                }
                try {
                    setValue(LocalDate.parse(text.trim(), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                } catch (DateTimeParseException e) {
                    throw new IllegalArgumentException("日期格式错误，请使用 yyyy-MM-dd 格式", e);
                }
            }
        });
    }

    /**
     * 显示添加物品页面
     */
    @GetMapping("/add")
    public String showAddForm(Model model, @AuthenticationPrincipal User user) {
        // 创建空的ItemDto对象供表单绑定
        model.addAttribute("itemDto", new ItemDto());
        
        // 获取用户可见的分类列表
        List<Category> categories = categoryService.getAllCategoriesForUser(user.getId());
        model.addAttribute("categories", categories);
        
        model.addAttribute("user", user);
        return "item/add";
    }

    /**
     * 处理添加物品表单提交
     */
    @PostMapping("/add")
    public String addItem(@Valid @ModelAttribute ItemDto itemDto, 
                         BindingResult bindingResult,
                         @AuthenticationPrincipal User user,
                         Model model,
                         RedirectAttributes redirectAttributes) {
        
        // 如果有验证错误，返回表单页面
        if (bindingResult.hasErrors()) {
            List<Category> categories = categoryService.getAllCategoriesForUser(user.getId());
            model.addAttribute("categories", categories);
            model.addAttribute("user", user);
            return "item/add";
        }

        try {
            // 将DTO转换为实体
            Item item = convertDtoToEntity(itemDto, user.getId());
            
            // 保存物品
            boolean success = itemService.save(item);
            
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "物品添加成功！");
                return "redirect:/dashboard";
            } else {
                model.addAttribute("errorMessage", "物品添加失败，请重试。");
            }
        } catch (Exception e) {
            model.addAttribute("errorMessage", "添加物品时发生错误：" + e.getMessage());
        }

        // 如果失败，重新显示表单
        List<Category> categories = categoryService.getAllCategoriesForUser(user.getId());
        model.addAttribute("categories", categories);
        model.addAttribute("user", user);
        return "item/add";
    }

    /**
     * 显示编辑物品页面
     */
    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, 
                              Model model, 
                              @AuthenticationPrincipal User user,
                              RedirectAttributes redirectAttributes) {
        
        Item item = itemService.getById(id);
        
        // 检查物品是否存在且属于当前用户
        if (item == null || !item.getUserId().equals(user.getId())) {
            redirectAttributes.addFlashAttribute("errorMessage", "物品不存在或无权限访问。");
            return "redirect:/dashboard";
        }

        // 转换为DTO
        ItemDto itemDto = convertEntityToDto(item);
        model.addAttribute("itemDto", itemDto);
        
        // 获取分类列表
        List<Category> categories = categoryService.getAllCategoriesForUser(user.getId());
        model.addAttribute("categories", categories);
        
        model.addAttribute("user", user);
        return "item/edit";
    }

    /**
     * 处理编辑物品表单提交
     */
    @PostMapping("/edit/{id}")
    public String editItem(@PathVariable Long id,
                          @Valid @ModelAttribute ItemDto itemDto,
                          BindingResult bindingResult,
                          @AuthenticationPrincipal User user,
                          Model model,
                          RedirectAttributes redirectAttributes) {
        
        Item existingItem = itemService.getById(id);
        
        // 检查物品是否存在且属于当前用户
        if (existingItem == null || !existingItem.getUserId().equals(user.getId())) {
            redirectAttributes.addFlashAttribute("errorMessage", "物品不存在或无权限访问。");
            return "redirect:/dashboard";
        }

        // 如果有验证错误，返回表单页面
        if (bindingResult.hasErrors()) {
            List<Category> categories = categoryService.getAllCategoriesForUser(user.getId());
            model.addAttribute("categories", categories);
            model.addAttribute("user", user);
            return "item/edit";
        }

        try {
            // 更新物品信息
            Item item = convertDtoToEntity(itemDto, user.getId());
            item.setId(id);
            item.setCreatedAt(existingItem.getCreatedAt()); // 保持原创建时间
            item.setUpdatedAt(LocalDateTime.now());
            
            boolean success = itemService.updateById(item);
            
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "物品更新成功！");
                return "redirect:/dashboard";
            } else {
                model.addAttribute("errorMessage", "物品更新失败，请重试。");
            }
        } catch (Exception e) {
            model.addAttribute("errorMessage", "更新物品时发生错误：" + e.getMessage());
        }

        // 如果失败，重新显示表单
        List<Category> categories = categoryService.getAllCategoriesForUser(user.getId());
        model.addAttribute("categories", categories);
        model.addAttribute("user", user);
        return "item/edit";
    }

    /**
     * 删除物品
     */
    @PostMapping("/delete/{id}")
    public String deleteItem(@PathVariable Long id,
                            @AuthenticationPrincipal User user,
                            RedirectAttributes redirectAttributes) {
        
        Item item = itemService.getById(id);
        
        // 检查物品是否存在且属于当前用户
        if (item == null || !item.getUserId().equals(user.getId())) {
            redirectAttributes.addFlashAttribute("errorMessage", "物品不存在或无权限删除。");
            return "redirect:/dashboard";
        }

        try {
            boolean success = itemService.removeById(id);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "物品删除成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "物品删除失败，请重试。");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "删除物品时发生错误：" + e.getMessage());
        }

        return "redirect:/dashboard";
    }

    /**
     * 将DTO转换为实体
     */
    private Item convertDtoToEntity(ItemDto dto, Long userId) {
        Item item = new Item();
        item.setName(dto.getName());
        item.setDescription(dto.getDescription());
        item.setCategoryId(dto.getCategoryId());
        item.setPrice(dto.getPrice());
        item.setPurchaseDate(dto.getPurchaseDate());
        item.setUserId(userId);
        item.setCreatedAt(LocalDateTime.now());
        item.setUpdatedAt(LocalDateTime.now());
        return item;
    }

    /**
     * 将实体转换为DTO
     */
    private ItemDto convertEntityToDto(Item item) {
        ItemDto dto = new ItemDto();
        dto.setId(item.getId());
        dto.setName(item.getName());
        dto.setDescription(item.getDescription());
        dto.setCategoryId(item.getCategoryId());
        dto.setPrice(item.getPrice());
        dto.setPurchaseDate(item.getPurchaseDate());
        return dto;
    }
}
